package com.sunnyweather.android.logic.dao

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import com.google.gson.Gson
import com.sunnyweather.android.SunnyWeatherApplication
import com.sunnyweather.android.logic.model.Place
import com.sunnyweather.android.logic.util.LogUtil
import kotlin.reflect.typeOf

object PlaceDao {

    //暂存所有已经保存的地址的数量
    var index=sharedPreference().getInt("Index",0)

    fun setPlace(place: Place){
        sharedPreference().edit {
            putString("place",Gson().toJson(place))
        }
    }

    fun getRestoredPlace():Place= Gson().fromJson(sharedPreference().getString("place",""),Place::class.java)

    fun isStored():Boolean= sharedPreference().contains("place")

    fun addPlace(place: Place){
        sharedPreference().edit {
            LogUtil.d("PlaceDao.addPlace",place.toString())
            putString("$index",Gson().toJson(place))
            putInt("Index", index+1)
        }
        index++
        LogUtil.d("PlaceDao.showIndex", index.toString())
    }

    fun removePlace(key:String){
        for(i in key.toInt()+1 until index ){
            val value= sharedPreference().getString("$i","")
            sharedPreference().edit {
                putString("${i-1}",value)
            }
        }
        sharedPreference().edit {
            remove("${index-1}")
            putInt("Index",index-1)
        }
        index--
    }

    fun removeAllPlaces(){
        sharedPreference().edit {
            putInt("Index",0)
        }
    }

    fun getPlaceFromList(key:String):Place=Gson().fromJson(sharedPreference().getString(key,""),Place::class.java)

    private fun sharedPreference()=SunnyWeatherApplication.context.getSharedPreferences("sunny_weather",Context.MODE_PRIVATE)
}